<!-- 
 * 用户管理
 * @author: 冯宇
 * @since: 2022-04-29
 * index.vue
-->
  <template>
  <div class="user-manage-container h100">
    <Filters :formModel="data.formModel" :formLabel="data.formLabel" @reset="resizeForm" @filter="getUserList">
    </Filters>

    <TableCom :tableHeader="data.tableHeader" :tableData="data.tableData" :btnData="data.btnData"
      @getCurrentChange="getCurrentChange" @comEvent="comEvent" @getSelectChange="getSelectChange"
      :isShowCheckbox="true" @colSelect="colSelect" @refresh="refreshTable" :pagination="data.pagination"
      :loading="data.loading" handleWidth="226" @getSizeChange="getSizeChange">
      <el-button v-for="(item, index) in data.btnList" :key="index" class="tableBtnCss"
        :style="{ backgroundColor: item.bgColor }" @click="userManageBtnList(index)">
        <svg-icon :name="item.icon" v-if="item.icon"></svg-icon>
        {{ item.name }}
      </el-button>
    </TableCom>

    <!-- 上传文件 -->
    <!-- <el-dialog v-model="isShowLead" title="批量导入用户" width="30%" :before-close="() => (isShowLead = false)">
      <uploadDownload @upload="uploadFile"></uploadDownload>
    </el-dialog> -->

    <!-- 重置密码 -->
    <el-dialog width="34%" v-model="data.dialogPassword">
      <template #title>
        <div style="font-weight: 700; font-size: 20px">{{ data.dialogPasswordTitle }}</div>
      </template>
      <div class="reset-password">
        <div class="content">
          <span>用户名称：</span>
          <span>{{ data.userReset.userName }}</span>
        </div>
        <div class="content">
          <span>用户密码已重置为：</span>
          <span class="pass">{{ data.userReset.password }}</span>
        </div>
        <div class="content">请牢记，下次登录请使用该密码登录</div>
        <div class="button">
          <el-button type="primary" @click="data.dialogPassword = false">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-drawer v-model="data.rightDrawer" destroy-on-close>
      <template #title>
        <div class="edit-title">
          <div class="title-icon"></div>
          <div class="title-text">{{ data.rightDrawerTitle }}用户</div>
        </div>
      </template>

      <template #default>
        <el-form class="edit-content" :model="data.editForm" :rules="data.editFormRules" ref="editFormDom">
          <el-form-item label="用户账号：" prop="userName" v-if="data.rightDrawerTitle === '新增'">
            <el-input v-model="data.editForm.userName" placeholder="请输入用户账号" clearable />
            <div class="tips">
              <span>最大长度30个字符，允许中文、英文字母、数字</span>
              <span>{{ data.editForm.userName ? data.editForm.userName.length : 0 }}/30</span>
            </div>
          </el-form-item>
          <el-form-item label="姓名：" prop="realName" v-if="data.rightDrawerTitle === '新增'">
            <el-input v-model="data.editForm.realName" placeholder="请输入姓名" clearable />
            <div class="tips">
              <span>最大长度30个字符，允许中文、英文字母、数字</span>
              <span>{{ data.editForm.realName ? data.editForm.realName.length : 0 }}/30</span>
            </div>
          </el-form-item>


          <el-form-item label="用户账号：" v-if="data.rightDrawerTitle === '编辑'">
            <el-input v-model="data.editForm.userName" placeholder="请输入用户账号" clearable :disabled="true" />
            <div class="tips">
              <span>最大长度30个字符，允许中文、英文字母、数字</span>
              <span>{{ data.editForm.userName ? data.editForm.userName.length : 0 }}/30</span>
            </div>
          </el-form-item>
          <el-form-item label="姓名：" v-if="data.rightDrawerTitle === '编辑'">
            <el-input v-model="data.editForm.realName" placeholder="请输入姓名" clearable :disabled="true" />
            <div class="tips">
              <span>最大长度30个字符，允许中文、英文字母、数字</span>
              <span>{{ data.editForm.realName ? data.editForm.realName.length : 0 }}/30</span>
            </div>
          </el-form-item>


          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="data.editForm.mobile" placeholder="请输入手机号码" clearable />
            <div class="tips">
              <span>只允许填写11位数字</span>
            </div>
          </el-form-item>
          <el-form-item label="角色：" prop="userRoleId">
            <el-table :data="data.rowSelectList" border @selection-change="checkRole" ref="editTable" :row-key="getRowKey">
              <el-table-column v-if="data.rightDrawerTitle == '新增'" width="40" type="selection" />
              <el-table-column v-else width="60" type="selection" align="center" :reserve-selection="true"/>
              <el-table-column type="index" width="60" label="序号" align="center" />
              <el-table-column prop="rolename" label="角色名称" align="center" />
              <el-table-column prop="rolenode" label="角色描述" align="center" />
            </el-table>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" size="large" style="width: 120px" @click="userEdit">提交</el-button>
          <el-button size="large" style="width: 120px" @click="data.rightDrawer = false">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup >
import { reactive, ref, nextTick } from 'vue'
import { getUserListApi, resetPasswordApi, addNewUserApi, delUserApi, editUserValidApi, editAllUserValidApi, userInfoEditApi } from '@/api/interface/userManage.js'
import { getAllRoleList } from '@/api/interface/role.js'
import { colFilters, batchHandle, tableIsEnable, lineHandle ,deepClone} from '@/utils/common.js'

import { ElMessageBox, ElMessage } from 'element-plus'
const editTable = ref(null)
const editFormDom = ref(null)
const isShowLead = ref(false)

const data = reactive({
  formModel: {
    userName: '',
    realName: '',
    mobile: '',
    valid: '',
    roleId: '',
  },
  formLabel: [
    {
      label: '用户账号',
      model: "userName",
      type: "text",
      width: '160',
      placeholder: '请输入用户账号',
    },
    {
      label: '姓名',
      model: "realName",
      type: "text",
      width: '160',
      placeholder: '请输入姓名',
    },
    {
      label: '手机号码',
      model: "mobile",
      type: "text",
      width: '160',
      placeholder: '请输入手机号',
    },
    {
      label: '用户角色',
      model: "roleId",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
      ],
    },
    {
      label: '用户状态',
      model: "valid",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
        {
          key: '启用',
          value: true
        },
        {
          key: '禁用',
          value: false
        },
      ],
    },

  ],
  editForm: {
    userName: '',
    realName: '',
    mobile: '',
    userRoleId: [],
    valid: false,
    userId:''
  },
  rowSelectList: [],
  editFormRules: {
    userName: {
      required: true,
      validator: (rule, value, callback) => {
        if (/^[\u4e00-\u9fa5/a-zA-Z0-9_-]{3,30}$/.test(value) == false) {
          callback(new Error('请输入正确的账号'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
    realName: {
      required: true,
      validator: (rule, value, callback) => {
        if (/^[\u4e00-\u9fa5/a-zA-Z0-9_-]{2,30}$/.test(value) == false) {
          callback(new Error('请输入正确的姓名'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
    mobile: {
      required: true,
      validator: (rule, value, callback) => {
        if (/^1\d{10}$/.test(value) == false) {
          callback(new Error('请输入11位手机号'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
    userRoleId: { required: true, message: '请选择用户角色', trigger: 'change' },
  },
  roleList: [],
  btnList: [
    {
      name: '新增用户',
      icon: '',
      bgColor: '#25D390',
    },
    // {
    //   name: '批量导入用户',
    //   bgColor: '#00A2FF',
    // },
    // {
    //   name: '导出全量用户',
    //   bgColor: '#00A2FF',
    // },
    // {
    //   name: '导出选中用户',
    //   bgColor: '#00A2FF',
    // },
    {
      name: '批量启用',
      bgColor: '#00A2FF',
    },
    {
      name: '批量禁用',
      bgColor: '#FFB018',
    },
    {
      name: '批量删除',
      bgColor: '#F74B33',
    },
  ],
  tableHeader: [
    {
      label: '用户账号',
      prop: 'userName',
    },
    {
      label: '姓名',
      prop: 'realName',
    },
    {
      label: '手机号码',
      prop: 'mobile',
    },
    {
      label: '用户角色',
      prop: 'userRoleName',
    },
    {
      label: '用户状态',
      prop: 'userStatus',
    },
    {
      label: '登录次数',
      prop: 'loginCount',
    },
    {
      label: '注册时间',
      prop: 'registerTime',
    }

  ],
  tableData: [],
  btnData: [
    {
      name: '编辑',
      color: '#25D390',
      change: 'edit',
    },
    {
      name: '重置密码',
      color: '#00A2FF',
      change: 'reset',
    },
    {
      name: '删除',
      color: '#F74B33',
      change: 'del',
    },
    {
      name: '是否启用',
      isStart: true,
      prop: 'valid',
      change: 'enable',
    },
  ],
  currentSelectList: [],
  pagination: {
    currentPage: 1,
    size: 10,
    total: 0,
  },
  userReset: {
    userName: '',
    password: '',
  },
  dialogPasswordTitle: '',
  dialogPassword: false,
  rightDrawerTitle: '',
  rightDrawer: false,
  loading:false,
})


//用户列表及用户查询
const getUserList = () => {
  data.loading = true
  const params = {
    ipi: data.pagination.currentPage,
    ips: data.pagination.size,
    userName: data.formModel.userName,
    mobile: data.formModel.mobile,
    valid: data.formModel.valid,
    realName: data.formModel.realName,
    roleId: data.formModel.roleId,
  }
  getUserListApi(params).then((res) => {
    const arr = res.data.result.map(v => {
      v.userStatus === 0 ? v.userStatus = '启用' : v.userStatus = '禁用'
      v.userRoleName = v.userRoleName.join(',')
      return v
    })
    data.loading = false
    data.tableData = arr
    data.pagination.total = res.data.total
  })
}
getUserList()
//重置搜索条件
const resizeForm = () => {
  for (let key in data.formModel) {
    data.formModel[key] = ''
  }
  getUserList()
}



//角色列表
const getAllRole = () => {
  const params = {
    ipi: 1,
    ips: 20,
    rolename: '',
    valid: '',
  }
  getAllRoleList(params).then((res) => {
    if (res.status === 200) {
      data.rowSelectList = deepClone(res.data.result)
      let arr = res.data.result.map(v => ({
        key: v.rolename,
        value: v.id
      }))
      for (let v of data.formLabel) {
        if (v.model == 'roleId') {
          v.option = [...v.option, ...arr]
          break
        }
      }
    }
  })
}
getAllRole()


const getRowKey = (row)=>{
  return row.id + ''
}
//角色列表操作
const checkRole = (changeArr) => {
  data.editForm.userRoleId = changeArr.map((v) => v.id)
}
//添加and编辑用户
const userEdit = () => {
  if (data.rightDrawerTitle == '新增') {
    ElMessageBox.confirm('是否添加该用户?').then(() => {
      nextTick(() => {
        editFormDom.value.validate((bool) => {
          if (bool) {
            const params = {
              userName: data.editForm.userName,
              realName: data.editForm.realName,
              mobile: data.editForm.mobile,
              userRoleId: data.editForm.userRoleId,
              valid: false,
            }
            addNewUserApi(JSON.stringify(params)).then((res) => {
              if (res.status === 200) {
                data.dialogPasswordTitle = '添加成功'
                data.userReset.userName = params.userName
                data.userReset.password = res.data
                data.rightDrawer = false
                data.dialogPassword = true
                getUserList()
              } else {
                return
              }
            })
          } else {
            return
          }
        })
      })
    })
  } else if (data.rightDrawerTitle == '编辑') {
    ElMessageBox.confirm('确认修改该用户信息？').then(() => {
      nextTick(() => {
        editFormDom.value.validate((bool) => {
          if (bool) {
            const params = {
              userName: data.editForm.userName,
              realName: data.editForm.realName,
              mobile: data.editForm.mobile,
              userRoleId: data.editForm.userRoleId,
              valid: data.editForm.valid,
              userId:data.editForm.userId
            }
            userInfoEditApi(JSON.stringify(params)).then((res) => {
              if (res.status === 200) {
                data.rightDrawer = false
                ElMessage({
                  message: res.message,
                  type: 'success',
                })
                getUserList()
              }
            })
          } else {
            return
          }
        })
      })
    })
  }
}




//列筛选
const colSelect = (headerArr, type, e, currentItem) => {
  if (type === 'filter') {
    const currentData = colFilters(headerArr, e, currentItem, data.tableHeader)
    data.tableHeader = currentData
  } else {
    //全选/全取消
    data.tableHeader = headerArr
  }
}
//刷新
const refreshTable = () => {
  getUserList()
}
//表头功能
const userManageBtnList = (index) => {
  switch (index) {
    case 0:
      data.rightDrawerTitle = '新增'
      data.editForm.userName = ''
      data.editForm.realName = ''
      data.editForm.mobile = ''
      data.editForm.userRoleId = []
      data.editForm.valid = false
      nextTick(() => {
        data.rowSelectList.forEach((v) => {
          editTable.value.toggleRowSelection(v, false)
        })
      })
      data.rightDrawer = true
      break
    // case 1:
    //   isShowLead.value = true
    //   console.log('通过文件批量导入')
    //   break
    // case 2:
    //   console.log('导出全部用户')
    //   break
    // case 3:
      // console.log('导出选中')
      // break
    case 1:
      const startArr = data.currentSelectList.map((v) => +v.userId)
      const startFunction = () => {
        const start = {
          userIds: startArr,
          type: 'start',
        }
        editAllUserValidApi(JSON.stringify(start)).then((res) => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getUserList()
          }
        })
      }
      batchHandle(startArr, 'START', startFunction)
      break
    case 2:
      const stopArr = data.currentSelectList.map((v) => +v.userId)
      const stopFunction = () => {
        const stop = {
          userIds: stopArr,
          type: 'stop',
        }
        editAllUserValidApi(JSON.stringify(stop)).then((res) => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getUserList()
          }
        })
      }
      batchHandle(stopArr, 'STOP', stopFunction)
      break
    case 3:
      const delArr = data.currentSelectList.map((v) => +v.userId)
      const delFunction = () => {
        const del = {
          userIds: delArr,
          type: 'del',
        }
        editAllUserValidApi(JSON.stringify(del)).then((res) => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getUserList()
          }
        })
      }
      batchHandle(delArr, 'DEL', delFunction)
      break
    default:
      break
  }
}
//勾选用户
const getSelectChange = (row) => {
  data.currentSelectList = row
}
//分页
const getCurrentChange = (page) => {
  data.pagination.currentPage = page
  getUserList()
}
//每页多少条
const getSizeChange = (size) => {
  data.pagination.size = size
  getUserList()
}



//行内功能
const comEvent = (type, row) => {
  if (type == 'edit') {
    data.rightDrawerTitle = '编辑'
    data.editForm.userName = row.userName
    data.editForm.realName = row.realName
    data.editForm.mobile = row.mobile
    data.editForm.userRoleId = row.userRoleId
    data.editForm.valid = row.valid
    data.editForm.userId = row.userId
    data.rightDrawer = true
    nextTick(() => {
      editTable.value.clearSelection()
      data.editForm.userRoleId.forEach(v=>{
        data.rowSelectList.forEach((vv,i)=>{
          if(v==vv.id){
            // editTable.value.toggleRowSelection(data.rowSelectList[i],true)
            editTable.value.toggleRowSelection(vv,true)
          }
        })
      })
    })

  } else if (type == 'reset') {
    ElMessageBox.confirm('是否重置该用户密码?').then(() => {
      resetPasswordApi(row.userId).then((res) => {
        if (res.status === 200) {
          data.dialogPasswordTitle = '重置密码'
          data.userReset.userName = row.userName
          data.userReset.password = res.data
          data.dialogPassword = true
        }
      })
    })
  } else if (type == 'del') {
    const delFunction = () => {
      delUserApi(row.userId).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: '已删除该用户',
            type: 'success',
          })
          getUserList()
        }
      })
    }
    tableIsEnable(data.tableData, 'del', row, delFunction)
  } else if (type == 'enable') {
    const enableFunction = () => {
      editUserValidApi({ userId: row.userId, valid: !row.valid }).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: res.message,
            type: 'success',
          })
          getUserList()
        }
      })
    }
    lineHandle(row, 'valid', enableFunction)
  }
}



//上传文件
const uploadFile = (data) => {
  console.log(data, 'data');

}
</script>

<style lang="scss" scoped>
.user-manage-container {
  box-sizing: border-box;
  overflow-y: scroll;
  .reset-password {
    .content {
      margin-bottom: 20px;

      .pass {
        color: red;
        font-weight: 700;
      }
    }

    .button {
      text-align: right;
    }
  }

  .edit-title {
    display: flex;
    .title-icon {
      width: 8px;
      height: 18px;
      background-color: #00a2ff;
      margin-right: 6px;
    }

    .title-text {
      font-weight: 700;
      color: #333;
      font-size: 18px;
    }
  }

  .edit-content {
    padding: 0 30px;

    .el-form-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-bottom: 16px;

      .tips {
        display: flex;
        justify-content: space-between;
        width: 100%;
        font-size: 12px;
        color: #999;
        line-height: 16px;
        margin-top: 2px;
      }

      ::v-deep .el-form-item__label {
        font-weight: 700;
        font-size: 14px;
        color: #333;
      }

      ::v-deep .el-form-item__content {
        width: 100%;
      }

      ::v-deep .el-input__inner {
        font-weight: 700;
      }

      ::v-deep .el-input__inner::placeholder {
        font-weight: 400;
        color: #a3adc5;
      }
    }
  }
}
</style>
